// pages/Featured/main/index.js
const app = getApp()
const utils = require('../../../utils/util')
const dataHandler = require('./dataHandler.js')
const isIphoneX = wx.getSystemInfoSync().safeArea.top > 20 && wx.getSystemInfoSync().model.indexOf('iPhone') > -1 ? true : false
const _bottom = isIphoneX ? 82 : 49

const menuData = [ {
    styleTitle: "风格",
    styleValue: null,
    styleMenuItemId: 'all-style',
    spaceTitle:'空间',
    spaceValue: null,
    spaceMenuItemId: 'all-space',
    categoryTitle: '品类',
    categoryValue: null,
    categoryMenuItemId:'all-category',
    livingRoomTitle: "居室",
    livingRoomValue: null,
    livingRoomMenuItemId: 'all-livingRoom',
  },{
    styleTitle: "风格",
    styleValue: null,
    styleMenuItemId: 'main-style',
  },{
    styleTitle: "风格",
    styleValue: null,
    styleMenuItemId: 'product-style',
    spaceTitle:'空间',
    spaceValue: null,
    spaceMenuItemId: 'product-space',
  },{},{
    styleTitle: "风格",
    styleValue: null,
    styleMenuItemId: 'new-style',
    seriesTitle: "系列",
    seriesValue: null,
    serieseMenuItemId: 'new-series',
  }]
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navHeight: app.globalData.navHeight,
    bottom: _bottom,
    fliterBoxH:106,
    height:'',
    topActiveIndex: 0, // 方案类型
    isRefresh: false, // 是否刷新数据
    hasNoMore: false, // 是否有数据
    oneSpace: '', //空间
    allHouseData: {}, // 风格 居室 家庭组成等数据集合
    oneSpaceList: [], // 空间集合
    categoryList: [], // 品类集合
    seriesList:[], // 系列集合
    menuData: menuData, // 筛选选中值
    allProgrammeList: [], // 全部 列表
    allPage: 1, // 全部 分页数
    mainProgrammeList: [], // 主推样板间 列表
    mainPage: 1, // 主推样板间 分页数 
    productProgrammeList: [], // //单空间案例 列表
    productPage: 1, //单空间案例 分页数
    packageList:[], // 套餐方案 列表
    newPage: 1, // 新品方案 分页数
    newProgrammeList: [], // // 新品方案 列表
    serialName:'', // 系列名称
    toView:'', // 新品方案定位
    typeList: [{ // 方案类型
      name: '全部',
      value: 0
    },  {
      name: '臻选样板间',
      value: 1
    }, {
      name: '单空间案例',
      value: 2
    }, {
      name: '套餐方案',
      value: 3
    }, {
      name: '新品方案',
      value: 4
    }],
    scroll_height: '100%',
    scrollTop: 0, // 新品方案 内容的滚动条距离顶部的距离
    scrollLeft: 0, // scroll-view 设置横向滚动条位置
  },
  setActive(e) {
    // console.log(e)
    // let active = e && e.target ? e.target.dataset.active : e
    let active = e && e.currentTarget ? e.currentTarget.dataset.active : e
    this.setData({
      topActiveIndex:active,
    })
    
    this.setupInit()
    // 全部
    if(active === 0){
      this.setData({
        topActiveIndex: active,
        hasNoMore: false
      })
      setTimeout(()=>{
        if(this.data.allProgrammeList.length === 0){
          this.getAllProgrammeData(1)
        }
      },300)
    }
    // 主推样板间
    if(active === 1){
      this.setData({
        topActiveIndex: active,
        hasNoMore: false
      })
      setTimeout(()=>{
        if(this.data.mainProgrammeList.length === 0){
          this.mainProgrammeData(1)
        }
      },300)
    }
    // 单空间案例
    if(active === 2){
      this.setData({
        topActiveIndex: active,
        hasNoMore: false
      })
      setTimeout(()=>{
        if(this.data.productProgrammeList.length === 0){
          this.productProgrammeData(1)
        }
      },300)
    }
    // 套餐方案
    if(active === 3) {
      this.setData({
        topActiveIndex: active,
        hasNoMore: false
      })
      setTimeout(() => {
        if(this.data.packageList.length === 0) {
          this.getPackageList()
        }
      },300)
    }

    // 新品方案
    if(active === 4) {
      this.setData({
        topActiveIndex: active,
        hasNoMore: false
      })
      setTimeout(()=>{
        if(this.data.newProgrammeList.length === 0) {
          this.newProgrammeData(1)
        }
      },300)
    }
    this.scrollLeftCompute()
  },
  //获取风格和居室
  GetAfflatusCondition() {
    utils.$http(app.globalData.api.GetAfflatusCondition, {}, 'GET', true, 'JSON').then(res => {
      if (res.data) {
        const SortData = JSON.parse(JSON.stringify(res.data))
        const allHouseData = dataHandler.handleAllHouseMenuListData(SortData)
        this.setData({
          allHouseData: allHouseData
        })
      }
    })
  },

  // 获取节点宽度 把之前的相加起来 等于滚动条距离left的距离
  // 设置滚动条的距离 
  scrollLeftCompute:function () {
      const currentIndex = this.data.topActiveIndex
      Promise.all([
        utils.getRect('.probtn', true),
        utils.getRect('.scroll-view_H')
    ]).then(([tabRects, navRect]) => {
        const tabRect = tabRects[currentIndex];
        const offsetLeft = tabRects
            .slice(0, currentIndex)
            .reduce((prev, curr) => prev + curr.width, 0);
        this.setData({
            scrollLeft: offsetLeft - (navRect.width - tabRect.width) / 2
        });
    });
  },

  //获取空间
  GetFeaturedAllOnespace(){
    utils.$http(app.globalData.api.GetFeaturedAllOnespace, {}, 'GET', true, 'JSON').then(res => {
      if (res.data) {
        const oneSpaceList = dataHandler.handleMenuListData(res.data, 'spaceName', 'spaceCode')
        this.setData({
          oneSpaceList : oneSpaceList, // 空间
        })
      }
    })
  },
   //根据空间获取品类
   GetFeaturedCategory(OneSpace){
    utils.$http(app.globalData.api.GetFeaturedCategory, {
      OneSpace,
    }, 'GET', true, 'JSON').then(res=>{
      if(res.data){
        let categoryList = dataHandler.handleMenuListData(res.data, 'categoryName', 'idk')
        this.setData({
          categoryList,
        })
      }
    })
  },
  //获取新品方案列表页
  GetFeaturedNewProductList(data){
    let styleIds=""
    if(JSON.stringify(data) !== '{}' && JSON.stringify(data) !== undefined ){
      let {styleId} = data
      styleIds= styleId
    }
    utils.$http(app.globalData.api.GetFeaturedNewProductList, {
      styleId:styleIds
    }, 'GET', true, 'JSON').then(res => {
      // console.log(res)
      if(res.data){
        let Newproduct = res.data
        this.setData({
          Newproduct
        })
      }
    })
  },
  // 套餐方案
  getPackageList(){
    utils.$http(app.globalData.api.GetFeaturedTeSetMeal, {}, 'GET', true, 'JSON').then(res => {
      if (res.data) {
        const packageList = res.data
        this.setData({
          isRefresh: false,
          hasNoMore: true,
          packageList
        })
      }
    })
  },

  setupInit: function () {
    utils.getFrameById('#headerFliters', (frame) => {
      // console.log('headerFliters:', frame)
      if (frame && frame.height) {
        this.setData({
          fliterBoxH: frame.height
        })
      }
    })

    utils.getFrameById('#navigationBar', (frame) => {
      // console.log('navigationBar:', frame)
      if (frame && frame.height) {
        this.setData({
          navHeight: frame.height
        })
      }
    })
  },
  // 全部方案 风格 空间 品类 居室 全部是 单选
  allMenuItemChange: function (e) {
    const optType = e.detail.optType
    const subIndex = e.detail.subIndex
    const data = e.detail.data
    this.selectComponent(e.detail.superId).toggle(); // 选中后关闭遮罩层

    const menu = this.data.menuData[this.data.topActiveIndex]

    if(subIndex === 0){
      menu.styleTitle = data.text
      menu.styleValue = data.value
    }
    if (subIndex === 1) {
      menu.spaceTitle = data.text
      menu.spaceValue = data.value
      menu.categoryTitle = "全部"
      menu.categoryValue = ""
      this.GetFeaturedCategory(data.value)
    }
    if (subIndex === 2) {
      menu.categoryTitle = data.text
      menu.categoryValue = data.value
    }
    if (subIndex === 3) {
      menu.livingRoomTitle = data.text
      menu.livingRoomValue = data.value
    }
    this.setData({
      menuData: this.data.menuData
    })
    this.data.allPage = 1
    this.getAllProgrammeData(1)
  },
  mainMenuItemChange(e) {
    const optType = e.detail.optType
    const subIndex = e.detail.subIndex
    const data = e.detail.data
    this.selectComponent(e.detail.superId).toggle();

    const menu = this.data.menuData[this.data.topActiveIndex]

    if(subIndex === 0){
      menu.styleTitle = data.text
      menu.styleValue = data.value
    }

    this.setData({
      menuData: this.data.menuData
    })
    this.data.mainPage = 1
    this.mainProgrammeData(1)
  },

  productMenuItemChange(e) {
    const optType = e.detail.optType
    const subIndex = e.detail.subIndex
    const data = e.detail.data
    this.selectComponent(e.detail.superId).toggle();

    const menu = this.data.menuData[this.data.topActiveIndex]

    if(subIndex === 0){
      menu.styleTitle = data.text
      menu.styleValue = data.value
    }
    if (subIndex === 1) {
      menu.spaceTitle = data.text
      menu.spaceValue = data.value
    }
    this.setData({
      menuData: this.data.menuData
    })
    this.data.productPage = 1
    this.productProgrammeData(1)
  },

  getSeriesList(styleId) {
    utils.$http(app.globalData.api.GetFeaturedNewSeries, {
      style:styleId,
    }, 'GET', true, 'JSON').then(res=>{
      if(res.data) {
        const list = dataHandler.handleMenuListData(res.data, 'seriesName', 'id')
        this.setData({
          seriesList: list,
        })
      }
    })
  },
  newMenuItemChange(e) {
    const optType = e.detail.optType
    const subIndex = e.detail.subIndex
    const data = e.detail.data
    this.selectComponent(e.detail.superId).toggle();

    const menu = this.data.menuData[this.data.topActiveIndex]

    if(subIndex === 0){
      menu.styleTitle = data.text
      menu.styleValue = data.value

      this.getSeriesList(data.value)
      menu.seriesTitle = '全部'
      menu.seriesValue = ''

      this.setData({serialName: ''})
    }
    if (subIndex === 1) {
      menu.seriesTitle = data.text
      menu.seriesValue = data.value

      this.setData({serialName: data.text})
      // this.setNewtoView(data.value)
    }
    this.setData({
      menuData: this.data.menuData,
    })

    
    // if(subIndex === 0) {
      this.data.newPage = 1
      this.newProgrammeData(1)
    // }
  },

    // 设置新品方案定位 id
    setNewtoView(id) {
      let toView = `New${id}`
      this.setData({
        toView,
      })
    },
    // 获取空间请求参数
    getAllProgramParams() {
      const {topActiveIndex} =  this.data
      const schemeMenu = this.data.menuData[topActiveIndex]
      
      const oneSpaceId = schemeMenu.spaceValue || ''
      const styleId = schemeMenu.styleValue || ''
      const category = schemeMenu.categoryValue || ''
      const livingRoom = schemeMenu.livingRoomValue || ''
  
      const mapTypeCode = {
        0: ["Main", "Product", "New", "Package"],
        1: ["Main"],
        2: ["Product"],
        3: ["Package"],
        4: ["New"],
      }
      const params = {
        category: category, // 品类
        livingRoom: livingRoom, // 居室
        oneSpaceId: oneSpaceId, // 空间
        styleId: styleId, // 风格
        programmeTypeCode: mapTypeCode[topActiveIndex], // 方案类型
        // ordertype: "",
        rows: 10, // 每页获取的数据量
        pageFlag: true,
      }
      return params
    },
  // 获取全部方案数据
  getAllProgrammeData(page, type="new"){
    const params = this.getAllProgramParams()
    params.page = page
    // console.log('page:', params)
    utils.$http(app.globalData.api.GetFeaturedAllProgramme, params, 'POST', false, "JSON").then((res) => {
      if (type === 'new') {
        this.setData({
          isRefresh: false,
          allProgrammeList: res.data.records,
          hasNoMore: false
        })

      } else {
        if(res.data && res.data.records && res.data.records.length === 0){
            this.setData({
              hasNoMore:true
            })
        }else{
          const list = this.data.allProgrammeList.concat(res.data.records)
          this.setData({
            allProgrammeList: list
          })
        }
      }
    }).catch (() => {
      this.setData({
        isRefresh: false
      })
    })
  },
  // 获取主推样板间方案数据
  mainProgrammeData(page, type="new"){
    const params = this.getAllProgramParams()
    params.page = page
    // console.log('page:', params)
    utils.$http(app.globalData.api.GetFeaturedAllProgramme, params, 'POST', false, "JSON").then((res) => {
      if (type === 'new') {
        this.setData({
          isRefresh: false,
          mainProgrammeList: res.data.records,
          hasNoMore: false
        })

      } else {
        if(res.data && res.data.records && res.data.records.length === 0){
            this.setData({
              hasNoMore:true
            })
        }else{
          const list = this.data.mainProgrammeList.concat(res.data.records)
          this.setData({
            mainProgrammeList: list
          })
        }
      }
    }).catch (() => {
      this.setData({
        isRefresh: false
      })
    })
  },
  // 获取 单空间案例 方案数据
  productProgrammeData(page, type="new"){
    const params = this.getAllProgramParams()
    params.page = page
    // console.log('page:', params)
    utils.$http(app.globalData.api.GetFeaturedAllProgramme, params, 'POST', false, "JSON").then((res) => {
      if (type === 'new') {
        this.setData({
          isRefresh: false,
          productProgrammeList: res.data.records,
          hasNoMore: false
        })
      } else {
        if(res.data && res.data.records && res.data.records.length === 0){
            this.setData({
              hasNoMore:true
            })
        } else {
          const list = this.data.productProgrammeList.concat(res.data.records)
          this.setData({
            productProgrammeList: list
          })
        }
      }
    }).catch (() => {
      this.setData({
        isRefresh: false
      })
    })
  },
  // 获取 新品方案 方案数据
  newProgrammeData(page = 1, type="new") {
    const newMenu = this.data.menuData[this.data.topActiveIndex]
    const styleId = newMenu.styleValue || ''
    const seriesId = newMenu.seriesValue || ''
    
    const params = {
      styleId: styleId,
      seriesId: seriesId,
      rows: 6,
      page: page
    }

    utils.$http(app.globalData.api.GetFeaturedNewProductList, params, 'get', false, 'JSON').then(res => {
      if(res.success === 1 && res.data) {
        let { records = []} = res.data
        // this.setData({
        //   isRefresh: false,
        //   newProgrammeList: data,
        //   hasNoMore: false,
        //   // scrollTop: 0
        // })
        if (type === 'new') {
          this.setData({
            isRefresh: false,
            newProgrammeList: records,
            hasNoMore: false
          })
        } else {
          if(records && records.length === 0){
              this.setData({
                hasNoMore:true
              })
          } else {
            const list = this.data.newProgrammeList.concat(res.data.records)
            this.setData({
              newProgrammeList: list
            })
          }
        }
      }
    }).catch (() => {
      this.setData({
        isRefresh: false
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setupInit()
    const {id = '', name = '', active = 0} = options
    
    // let windowHeight = wx.getSystemInfoSync().windowHeight // 屏幕的高度
    // let windowWidth = wx.getSystemInfoSync().windowWidth // 屏幕的宽度
    // let ratio = 750 / windowWidth;
    // this.setData({
    //   scroll_height: (windowHeight-(windowWidth*90/750))*2+'rpx' 
    // })
    
    this.GetAfflatusCondition() // 风格 居室 家庭组成等
    this.GetFeaturedAllOnespace() // 空间
    this.setData({
      height: app.globalData.height,
    })
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
  
    if(active === '2' && name && id) { // 重上一页跳到单空间案例
      const menu = this.data.menuData[Number(active)]
      menu.spaceTitle = name
      menu.spaceValue = id
      
      this.setData({
        menuData: this.data.menuData
      })
    }
    this.setActive(Number(active))
    // this.getAllProgrammeData(1)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  loadNewData: function () {
    this.setData({
      isRefresh :true
    })
    const {topActiveIndex} = this.data
    // console.log(topActiveIndex)
    if (topActiveIndex === 0) {
      this.data.allPage = 1
      this.getAllProgrammeData(1)
    }
    if (topActiveIndex === 1) {
      this.data.mainPage = 1
      this.mainProgrammeData(1)
    }
    if(topActiveIndex === 2){
      this.data.productPage = 1
      this.productProgrammeData(1)
   }

   if(topActiveIndex === 3) {
    this.getPackageList()
   }

   if(topActiveIndex === 4) {
     this.data.newPage = 1
     this.newProgrammeData(1)
   }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  loadMoreData:function () {
     // 空间设计
     if(this.data.topActiveIndex === 0) {
       this.data.allPage = this.data.allPage + 1
       this.getAllProgrammeData(this.data.allPage, 'more')
     }
     if(this.data.topActiveIndex === 1) {
       this.data.mainPage = this.data.mainPage + 1
       this.mainProgrammeData(this.data.mainPage,'more')
     }
     if(this.data.topActiveIndex === 2) {
      this.data.productPage = this.data.productPage + 1
      this.productProgrammeData(this.data.productPage,'more')
     }

     if(this.data.topActiveIndex === 4) {
      this.data.newPage = this.data.newPage + 1
      this.newProgrammeData(this.data.newPage, 'more')
     }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})